from flask_restful import Resource, inputs
from flask_restful import marshal_with,reqparse,marshal
import werkzeug
#使用cache
from ext import cache

from . import models
#序列化对象
from . import serializer

parser = reqparse.RequestParser()
parser.add_argument('username',type=str,required=True,help='用户名必填',location=['form'])
parser.add_argument('password',type=inputs.regex(r'^\d{6,12}$'),required=True,help='密码必须是6-12位数字',location=['form'])
parser.add_argument('phone',type=inputs.regex(r'^1[345678]\d{9}$'),required=True,help='手机号码格式错误',location=['form'])
parser.add_argument('hobby',action='append')
# parser.add_argument('picture',type=werkzeug.datastructures.FileStorage,locations='file')
class UserResource(Resource):
    def post(self):
        username = parser.parse_args('username')
        password = parser.parse_args('password')
        phone = parser.parse_args('phone')
        hobby = parser.parse_args('hobby')
        print(hobby)
        return {'code':200,'msg':'ok'}

class BookResource(Resource):
    @marshal_with(serializer.book_fields)
    def get(self):
        books = models.BookModel.query.all()

        return books
    def post(self):
        return {'code': 200, 'name': 'post'}

class AuthorResource(Resource):
    @marshal_with(serializer.author_fields)
    def get(self):
        authors = models.AuthorModel.query.all()
        return authors
    def post(self):
        from util.model_exchange import model_to_dict_list
        authors = models.AuthorModel.query.all()
        dic = model_to_dict_list(authors)
        book = models.BookModel.query.all()
        dic2 = model_to_dict_list(queryset=book,fields=['id','name','price'])
        return {'code':200,'dic':dic,'dic2':dic2}